package com.groovy.domain

import com.groovy.model.User
import groovy.xml.XmlParser
import org.junit.Test

/***
 * see # http://www.groovy-lang.org/groovy-dev-kit.html#_reading_files
 */
class FileTest {

    @Test
    void testReader1() {
        //直接读取项目resource目录的指定文件名称
        def baseDir = FileTest.getClassLoader().getResource("test.txt").getPath()

        /**
         * 循环读取每一行进行读取.
         */
        new File(baseDir).eachLine { line, nb ->
            println "Line $nb: $line"
        }
    }

    @Test
    void testReader2() {
        //直接读取项目resource目录的指定文件名称
        def baseDir = FileTest.getClassLoader().getResource("test.txt").getPath()

        /**
         * 一次性获取文件所有内容，并指定编码
         */
        def fileText = new File(baseDir).getText("utf-8")
        println(fileText)
    }


    @Test
    void testReader3() {
        //指定路径目录,在指定文件名进行读取，此时的路径必须要知道在哪里
        def baseDir = "D:/devsoft/idea-workspace/groovy/out/production/resources/"

        /**
         * 循环读取每一行进行读取.
         */
        new File(baseDir, "test.txt").eachLine { line, nb ->
            println "Line $nb: $line"
        }
    }


    @Test
    void testWriter1() {
        // 此时会在项目工程的groovy/out/production/resources/目录先对test.txt文件操作
        // 建议指定一个磁盘目录,然后在指定文件名称进行写入,如：testWriter2
        def baseDir = FileTest.getClassLoader().getResource("test.txt").getPath()
        /**
         * 循环读取每一行进行读取.
         */
        new File(baseDir).withWriter("utf-8") { writer ->
            writer.writeLine 'Hello Groovy'
        }
    }

    @Test
    void testWriter2() {
        def baseDir = "D:/test/"

        /**
         * 循环读取每一行进行读取.
         */
        new File(baseDir, "test.txt").withWriter("utf-8") { writer ->
            writer.writeLine 'Hello Groovy'
        }
    }

    /**
     * 拷贝文件内容
     * @param sourcePath
     * @param dstPath
     */
    def copyFile(String sourcePath, String dstPath) {
        try {
            //判断不存在就,创建文件目录
            def dstFile = new File(dstPath)
            if (!dstFile.exists()) {
                dstFile.createNewFile()
            }
            //开始拷贝
            new File(sourcePath).withReader { reader ->
                //一次性读取所有信息
                def lines = reader.readLines()
                //写入目标文件
                dstFile.withWriter { writer ->
                    lines.forEach { line ->
                        //写入目标文件并且换行
                        writer.append(line).append("\r\n")
                    }
                }
            }

            return true
        } catch (Exception ex) {
            ex.printStackTrace()
        }
        return false
    }

    /**
     * 保存Object
     * @param obj
     * @param path
     */
    def saveObject(Object obj, String path) {
        try {
            def dstFile = new File(path)
            if (!dstFile.exists()) {
                dstFile.createNewFile()
            }
            dstFile.withObjectOutputStream {
                it.writeObject(obj)
            }
            return true
        } catch (Exception ex) {
            ex.printStackTrace()
        }
        return false
    }

    /**
     * 读取对象数据
     * @param path
     */
    def readObject(String path) {
        def obj = null
        try {
            def dstFile = new File(path)
            if (dstFile == null || !dstFile.exists()) return null
            //读取对象数据出来
            dstFile.withObjectInputStream {
                obj = it.readObject()
            }
        } catch (Exception ex) {
            ex.printStackTrace()
        }
        return obj
    }

    @Test
    void testReaderObject() {
        //读取出来并转换成User对象，语法与Kotlin类似
        def user = readObject("user.bin") as User
        println("userName=${user.userName},age=${user.age}")
    }

    @Test
    void testWriterObject() {
        def result = saveObject(user, "user.bin")
        println(result ? "成功" : "失败")
    }

    @Test
    void parseAndCreateFile(){
        def baseDir = FileTest.getClassLoader().getResource("book.xml").getPath()
        def sourceFile = new File(baseDir)

        def targetFile = new File("build", "gen/xml")
        targetFile.mkdirs()

        def xmlNode= new XmlParser().parse(sourceFile)

    }


}
